import { defineStore } from 'pinia';

const useSetting = defineStore('setting', {
  state: () => ({
    title: import.meta.env.VITE_APP_TITLE,
    favicon: import.meta.env.VITE_APP_TITLE,
    logo: import.meta.env.VITE_APP_LOGO,
    agreement: [
      {
        title: '用户协议',
        agreementSrc: 'https://avatars.githubusercontent.com/u/94167928',
      },
    ],
    logins: [
      {
        type: 'weixin',
        appId: 'weixin_1',
        typeName: '微信登录',
        logo: 'https://avatars.githubusercontent.com/u/94167928',
      },
      {
        appId: 'weibo_2',
        type: 'weibo',
        typeName: '微博登录',
        logo: 'https://avatars.githubusercontent.com/u/94167928',
      },
      {
        appId: 'qq_3',
        type: 'qq',
        typeName: 'qq登录',
        logo: 'https://avatars.githubusercontent.com/u/94167928',
      },
    ],
    isLoadSetting: false,
  }),
  getters: {
    getTitle(state) {
      return state.title;
    },
  },
  actions: {
    updateTitle(name: string) {
      if (name) {
        this.title = name;
      }
    },
    updateFavicon(faviconUrl: string) {
      if (faviconUrl) {
        this.favicon = faviconUrl;
        this.setFavicon(faviconUrl);
      }
    },
    updateLogo(logoUrl: string) {
      if (logoUrl) {
        this.logo = logoUrl;
      }
    },
    async setFavicon(faviconUrl: string) {
      document.head.querySelectorAll('link').forEach(link => {
        if (link.rel === 'icon') {
          link.parentNode?.removeChild(link);
        }
      });
      // 修改浏览器页签图标
      const link = document.createElement('link');
      link.rel = 'icon';
      link.href = faviconUrl;
      document.head.append(link);
    },
    updateAgreement(agreement: any[]) {
      if (agreement) {
        this.agreement = agreement;
      }
    },
    updateLogins(logins: any[]) {
      if (!logins) {
        this.logins = [];
        return;
      }
      this.logins = logins;
    },
    updateIsLoadSetting(isLoadSetting: boolean) {
      if (isLoadSetting) {
        this.isLoadSetting = isLoadSetting;
      }
    },
  },
  persist: {
    key: 'SYSTEM_SETTING',
    // 修改为 sessionStorage，默认为 localStorage
    storage: window.sessionStorage,
  },
});

export default useSetting;
